﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;

using System.Text;

namespace NetCore.ORM.EF
{
    public class EFRepository : IDbRepository
    {
        public DbContext Current {
            get {
                return _provider.DbContext;
            }
        }
        private ProviderType _ProviderType { get; set; }
        private EFDbRepository _entityFactory { get; set; }

        public ProviderType CurrentProviderType { get => _ProviderType; }

        private Provider _provider { get; set; }
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public bool DbEnsureCreated()
        {
           return _provider.DbContext.DbEnsureCreated();
        }
        ~EFRepository() {
            this.Close();
        }
        public EFRepository()
        {
            _provider= CreateInstance(ApplicationEnvironments.ProviderType, ApplicationEnvironments.Site.ConnectionString);

        }
        public EFRepository(ProviderType providerType,string conntionString )
        {
            _provider = CreateInstance(ApplicationEnvironments.ProviderType, conntionString, "");
          
        }
        public EFRepository(Provider provider)
        {
            this.Init(provider);
        }
        private void Init(Provider provider)
        {
            _provider.DbContext = provider.DbContext;
            _entityFactory = new EFDbRepository(this);
            _ProviderType = provider.DbContext.CurrentProviderType;
         
        }
        public Provider CreateInstance(ProviderType providerType, string conntionString)
        {
            return this.CreateInstance(providerType,conntionString,"");
        }
        private Provider CreateInstance(ProviderType providerType, string conntionString,string map_card)
        {
            List<string> args = new List<string>();
            if (!string.IsNullOrWhiteSpace(map_card))
            {
                args.Add(map_card);
            }
            switch (providerType)
            {
                case ProviderType.MySql:
                    _provider = ProviderFactory.CreateProvider(conntionString, typeof(Data.MySql), args);
                    break;
                case ProviderType.Oracle:
                    _provider = ProviderFactory.CreateProvider(conntionString, typeof(Data.Oracle), args);
                    break;
                case ProviderType.SQLite:
                    _provider = ProviderFactory.CreateProvider(conntionString, typeof(Data.SqLite), args);
                    break;
                default:
                    _provider = ProviderFactory.CreateProvider(conntionString, typeof(Data.SqlServer), args);
                    break;
            }
            Init(_provider);
            return _provider;
        }
        #region Execute
     
        public IDbTransaction Begin()
        {
            return _provider.DbContext.Begin();
        }
        public void Commit()
        {
            _provider.DbContext.Commit();
        }
        public void Rollback()
        {
            _provider.DbContext.Rollback();
        }
        public int Execute(string sqlCommand)
        {
            return _provider.DbContext.ExecuteNonQuery(sqlCommand);
        }


        public int Execute(string sqlCommand, DataParameterCollection parametersValues) {
            return _provider.DbContext.ExecuteNonQuery(sqlCommand, parametersValues!=null?parametersValues.ToArray():null);
        }

        public int ExecuteProcedure(string procedureName)
        {
            return _provider.DbContext.ExecuteProcedure(procedureName, null);
        }

        public int ExecuteProcedure(string procedureName,DataParameterCollection dbParameters)
        {
            return _provider.DbContext.ExecuteProcedure(procedureName, dbParameters != null ? dbParameters.ToArray() : null);
        }
        #endregion
        public TEntity GetById<TEntity>(object id) where TEntity : class, new()
        {
            return GetById<TEntity>(id,null,true);
        }

        public TEntity GetById<TEntity>(object id,Func<TEntity, TEntity> func) where TEntity : class, new()
        {
            return GetById<TEntity>(id, func, true);
        }
        public TEntity GetById<TEntity>(object id, Func<TEntity, TEntity> func, bool isCache=true) where TEntity : class, new()
        {
            if (id == null || string.IsNullOrWhiteSpace(id.ToString()))
            {
                return default(TEntity) ;
            }
            DbFactoryHelper action = new DbFactoryHelper(typeof(TEntity));
            if (isCache&&ApplicationEnvironments.Site.IsEntityCache)
            {
                var obj = AppHttpContext.CacheService.GetCache<TEntity>(action.GetEntityCacheKey(id.ToString()));
                if (obj != null)
                {
                    return obj;
                }
            }
            TEntity entity = _provider.DbContext.Find<TEntity>(id);
            if (entity!=null&&_provider.DbContext.Entry<TEntity>(entity)!=null)
            {
                _provider.DbContext.Entry<TEntity>(entity).State = EntityState.Detached;
            }
            if (entity!= null)
            {
                if (func != null)
                {
                    entity = func(entity);
                }
                if (ApplicationEnvironments.Site.IsEntityCache)
                {
                    action.SetCache(id.ToString(), entity);
                }
            }
            return entity;
            // dbContext.Remove();
        }
        
        public TEntity Select<TEntity>(ICriterion criterion) where TEntity : class, new()
        {
            var list = this.Query<TEntity>(criterion, null);
            if (list != null && list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        public TEntity Select<TEntity>(string hql, ICriterion criterion) where TEntity : class, new()
        {
            var list = this.Query<TEntity>(hql, criterion);
            if (list != null && list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        public bool Delete<TEntity>(TEntity entity) where TEntity : class,new()
        {
            return _entityFactory.Delete<TEntity>(entity);
        }
        public bool Delete<TEntity>(List<TEntity> entity) where TEntity : class, new()
        {
            return _entityFactory.Delete<TEntity>(entity);
        }
        
        public bool Delete<T>(ICriterion criterion, bool isupdated=true) where T : class, new()
        {
            var action = new DbFactoryHelper(typeof(T));

            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = criterion.ToString(ref dataParam);
            if (string.IsNullOrWhiteSpace(where))
            {
                throw new Exception("没有相关查询条件！");
            }

            int i = this.Execute(string.Format( action.GetDeleteSql(ref dataParam, isupdated) ," and " + where), dataParam);

            return i > 0;
        }

        
        public bool Delete<T>(string ids, bool isupdated=true) where T : class, new()
        {
            var action = new DbFactoryHelper(typeof(T));
            var primaryKey = action.EntityMap.DbFields.Where(x => x.IsPrimaryKey).FirstOrDefault();
            bool isString = true;
            if (primaryKey.ColumnType.ToLower() == "int")
            {
                isString = false;
            }
            object[] deleteIds = ids.Split(new char[] { ',', ';' });
            if (!isString)
            {
                deleteIds = Array.ConvertAll<string, object>(ids.Split(new char[] { ',', ';' }), x => int.Parse(x));
            }
            ICriterion where = Expression.In(action.EntityMap.PrimaryKey, deleteIds);
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string sql = action.GetDeleteSql(ref dataParam, isupdated);
            sql = string.Format(sql , " and "+ where.ToString(ref dataParam));
            int i = this.Execute(sql, dataParam);
            action.RemoveCacheEntity(typeof(T), deleteIds);
            return i > 0;
        }
        public bool Insert<TEntity>(TEntity entity) where TEntity : class, new()
        {
            string strError = "";
            var action = new DbFactoryHelper(entity.GetType());
            return Insert<TEntity>(entity, action,ref strError);
        }

        public bool Insert<TEntity>(TEntity entity,ref string strError) where TEntity : class, new()
        {
            var action = new DbFactoryHelper(entity.GetType());
            return Insert<TEntity>(entity, action,ref strError);
        }
        public bool Insert<TEntity>(TEntity entity,DbFactoryHelper action,ref string strError)where TEntity:class,new()
        {
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string sql = GetInsert(action, entity, ref dataParam);
            int result = 0;
            if (action.EntityMap.Identifier)
            {
                result = this.Scalar(sql, dataParam).ToInt();
                if (result > 0)
                {
                    action.SetValue(entity, action.EntityMap.PrimaryKey, result);
                }
            }
            else
            {
                result = this.Execute(sql, dataParam);
            }
            return result > 0;
        }
        public bool BatchInsert<TEntity>(List<TEntity> entities, ref string strError) where TEntity : class, new()
        {
            if (entities != null && entities.Count > 0)
            {
                var action = new DbFactoryHelper(entities[0].GetType());
                foreach (var entity in entities)
                {
                    if (!this.Insert<TEntity>(entity, action,ref strError))
                    {
                        return false;
                    }
                }

            }
            return true;
        }
        public bool Update<TEntity>(TEntity entity) where TEntity : class, new()
        {
            string strError = "";
            var action = new DbFactoryHelper(typeof(TEntity));
            return Update<TEntity>(entity, action,ref strError);
        }
        public bool Update<TEntity>(TEntity entity, ref string strError) where TEntity : class, new()
        {
            var action = new DbFactoryHelper(typeof(TEntity));
            return Update<TEntity>(entity, action,ref strError);
        }
        private bool Update<TEntity>(TEntity entity, DbFactoryHelper action, ref string strError) where TEntity : class,new()
        {
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string sql = action.GetUpdate(this, entity, null, ref dataParam, ref strError);
            if (string.IsNullOrWhiteSpace(sql))
            {
                return true;
            }
            var result = this.Execute(sql, dataParam);
            if (result > 0)
            {
                if (ApplicationEnvironments.Site.IsEntityCache)
                {
                    action.CacheMerge<TEntity>(entity);
                }
            }
            return result > 0;
        }

        public bool Update<TEntity>(List<TEntity> entities, ref string strError) where TEntity : class, new()
        {
            return BatchUpdate<TEntity>(entities,ref strError);
        }
        public bool BatchUpdate<TEntity>(List<TEntity> entities, ref string strError) where TEntity : class, new()
        {
            if (entities != null && entities.Count > 0)
            {
                var action = new DbFactoryHelper(entities[0].GetType());
                foreach (var entity in entities)
                {
                    if (!this.Update<TEntity>(entity, action, ref strError))
                    {
                        return false;
                    }
                }

            }
            return true;
        }
        /// <summary>
        /// 通过查询条件批量更新
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="criterion"></param>
        /// <returns></returns>
        public bool Update<TEntity>(TEntity entity, ICriterion criterion) where TEntity : class, new()
        {
            var action = new DbFactoryHelper(entity.GetType());
            string strError = "";
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string sql = action.GetUpdate(this, entity, criterion, ref dataParam, ref strError);
            if (string.IsNullOrWhiteSpace(sql))
            {
                return true;
            }
            var result = this.Execute(sql, dataParam);
           
            return result > 0;
        }
        public bool SaveOrUpdate<T>(T entity) where T : class, new()
        {
            string strError = "";
            return SaveOrUpdate(entity,ref strError);
        }

        public bool SaveOrUpdate<T>(T entity, ref string strError) where T : class, new()
        {
            var action = new DbFactoryHelper(entity.GetType());
            return SaveOrUpdate<T>(entity,action,ref strError);
        }

        private bool SaveOrUpdate<T>(T entity, DbFactoryHelper action, ref string strError) where T : class, new()
        {
            // var action = new ActionEntity(this._provider, entity.GetType());
            var id = action.GetPrimaryId(entity);
           
            bool isupdate = action.IsUpdate(entity);
            if (!isupdate)
            {
                T oldEntity = this.GetById<T>(id,null,false);
                isupdate = oldEntity != null;
            }
            if (!isupdate)
            {
                return this.Insert<T>(entity, action, ref strError);
            }
            else
            {
                return this.Update<T>(entity, action, ref strError);
            }
        }
        public bool BatchSave<T>(List<T> lstData) where T : class, new()
        {
            if (lstData != null && lstData.Count > 0)
            {
                var action = new DbFactoryHelper(lstData[0].GetType());
                string strError = "";
                //List<T> insertLst = new List<T>();
                //List<T> updateLst = new List<T>();
                foreach (var entity in lstData)
                {
                    //var id = action.GetPrimaryId(entity);
                    //bool isupdate = action.IsUpdate(entity);
                    //if (!isupdate)
                    //{
                    //    T oldEntity = this.GetById<T>(id);
                    //    isupdate = oldEntity != null;
                    //}
                   bool flag= this.SaveOrUpdate<T>(entity, action, ref strError);
                    if (!flag)
                    {
                        throw new Exception(entity.ToJson()+"保存出错");
                    }
                 
                }
                
            }
            return true;
        }

        public List<T> Query<T>(ICriterion criterion) where T : class, new()
        {
           return this.Query<T>( criterion,null);
        }
        public List<T> Query<T>(string sql,ICriterion criterion) where T : class, new()
        {
            return this.Query<T>(sql, criterion,null);
        }


        public List<T> Query<T>( ICriterion criterion, Order order) where T : class, new()
        {
            var action = new DbFactoryHelper(typeof(T));
            string sql = action.GetSelectSql();
            return this.Query<T>(sql, criterion,order);
        }
        public List<T> Query<T>(string sql, ICriterion criterion, Order order) where T : class, new()
        {
            List<T> lstT = new List<T>();

            if (string.IsNullOrWhiteSpace(sql))
                return null;
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = (criterion != null) ? criterion.ToString(ref dataParam) : "";
            if (!string.IsNullOrWhiteSpace(where))
            {
                where = " and " + where;
            }
            if (order != null)
            {
                where += " order by " + order.ToString();
            }
            sql = string.Format(sql, where);
            return _provider.DbContext.GetReader<T>(sql, dataParam);
        }

       public List<T> Query<T>(ICriterion criterion, Order order, int pageindex, int pageSize, ref int recordCount) where T : class, new()
        {
            DbFactoryHelper action = new DbFactoryHelper(typeof(T));
            List<T> lstT = new List<T>();
            if (pageindex > 0)
            {
                recordCount = this.RecordCount(action, criterion);
                if (recordCount <= 0)
                {
                    return lstT;
                }
            }
            string sql = _provider.DbContext.QueryPage(action, new Order[] { order }, pageindex, pageSize);
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = (criterion != null) ? criterion.ToString(ref dataParam) : "";
            if (!string.IsNullOrWhiteSpace(where))
            {
                where = " and " + where;
            }
            sql = string.Format(sql, where);

            return _provider.DbContext.GetReader<T>(sql, dataParam);
        }

        public List<T> Query<T>(string hql, ICriterion criterion, Order order, int pageindex, int pageSize, ref int recordCount) where T : class, new()
        {
            List<T> lstT = new List<T>();
            if (pageindex > 0)
            {
                recordCount =this.RecordCount(hql, criterion);
                if (recordCount <= 0)
                {
                    return lstT;
                }
            }
            string sql = _provider.DbContext.QueryPage(hql, new Order[] { order }, pageindex, pageSize);
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = (criterion != null) ? criterion.ToString(ref dataParam) : "";
            if (!string.IsNullOrWhiteSpace(where))
            {
                sql = string.Format(sql, " and " + where);
            }
            else
            {
                sql = string.Format(sql, "");
            }
            sql = string.Format(sql, where);


            return _provider.DbContext.GetReader<T>(sql,dataParam);
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <param name="criterion"></param>
        /// <returns></returns>
        public int RecordCount(DbFactoryHelper action, ICriterion criterion)
        {
            string sql = _provider.DbContext.RecordCount(action);
            if (string.IsNullOrWhiteSpace(sql))
                return 0;
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = (criterion != null) ? criterion.ToString(ref dataParam) : "";
            if (!string.IsNullOrWhiteSpace(where))
            {
                where = " and " + where;
            }
            sql = string.Format(sql, where);
            return this.Scalar(sql, dataParam).ToInt();
        }
        public int RecordCount(string hql, ICriterion criterion)
        {
            string sql = _provider.DbContext.RecordCount(hql);
            if (string.IsNullOrWhiteSpace(sql))
                return 0;
            DataParameterCollection dataParam = new DataParameterCollection(this);
            string where = (criterion != null) ? criterion.ToString(ref dataParam) : "";
            if (!string.IsNullOrWhiteSpace(where))
            {
                where = " and " + where;
            }
            sql = string.Format(sql, where);

            return this.Scalar(sql, dataParam).ToInt();
        }



        public LigerGrid Query<T>(string hql, LigerGrid ligerGrid, ICriterion criterion) where T : class, new()
        {
            int recordCount = 0;
            var WhereExpression = ligerGrid.WhereExpression;
            if (WhereExpression != null)
            {
                criterion = Expression.And(criterion, WhereExpression);
            }
            if (string.IsNullOrWhiteSpace(ligerGrid.sortOrder))
            {
                ligerGrid.sortOrder = "desc";
            }
            if (string.IsNullOrWhiteSpace(ligerGrid.sortName))
            {
                ligerGrid.sortName= EntityBase.__LastModifyDate;
            }
            Order order = (ligerGrid.sortOrder.ToLower() == "asc") ? Order.Asc(ligerGrid.sortName) : Order.Desc(ligerGrid.sortName);
            if (ligerGrid.pageSize > 0)
            {
                var result = Query<T>(hql, criterion, order, ligerGrid.pageIndex, ligerGrid.pageSize, ref recordCount);
                if (result == null)
                {
                    ligerGrid.Rows = new List<T>();
                }
                else
                {
                    ligerGrid.records = result.Count;
                    ligerGrid.Rows = result;
                }
            }
            else
            {
              var result = this.Query<T>(hql,criterion, order);
                ligerGrid.Rows = result;
                if (result != null)
                {
                    ligerGrid.records = result.Count;
                }
            }
            
            ligerGrid.Total = recordCount;
            return ligerGrid;

        }
        public LigerGrid Query<T>(LigerGrid grid, ICriterion criterion) where T : class, new()
        {
            int recordCount = 0;
            var WhereExpression = grid.WhereExpression;
            if (WhereExpression != null)
            {
                criterion = Expression.And(criterion, WhereExpression);
            }
            if (string.IsNullOrWhiteSpace(grid.sortOrder))
            {
                grid.sortOrder = "desc";
            }
            if (string.IsNullOrWhiteSpace(grid.sortName))
            {
                grid.sortName = EntityBase.__LastModifyDate;
            }
            Order order = (grid.sortOrder.ToLower() == "asc") ? Order.Asc(grid.sortName) : Order.Desc(grid.sortName);
            if (grid.pageSize > 0)
            {
                var result = Query<T>(criterion, order, grid.pageIndex, grid.pageSize, ref recordCount);
                if (result == null)
                {
                    grid.Rows = new List<T>();
                }
                else
                {
                    grid.records = result.Count;
                    grid.Rows = result;
                }
            }
            else
            {
                var result = this.Query<T>(criterion,order);
                grid.Rows = result;
                if (result != null)
                {
                    grid.records = result.Count;
                }
            }
            
            grid.Total = recordCount;
            return grid;
        }

        /// <summary>
        /// 获取ExecuteDataReader
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public IDataReader Reader(string sql, DataParameterCollection parameters)
        {
            return _provider.DbContext.ExecuteReader(sql,parameters.ToArray());
        }

        public object Scalar(string sql, DataParameterCollection parameters)
        {
            return _provider.DbContext.ExecuteScalar(sql, parameters.ToArray());
        }
        public object Scalar(string sql, ICriterion criterion)
        {
            DataParameterCollection dbParameters = new DataParameterCollection(this);
           string where= criterion!=null? criterion.ToString(ref dbParameters):"";
            sql= string.Format(sql, where);
            return this.Scalar(sql,dbParameters);
        }
        #region Edit

        /// <summary>
        /// 新增sql
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private string GetInsert(DbFactoryHelper dbFactory, object entity, ref DataParameterCollection parameter)
        {
            if (parameter == null)
                parameter = new DataParameterCollection(this);
            StringBuilder strsql = new StringBuilder();
            StringBuilder strParam = new StringBuilder();
            strsql.Append(" insert into " + dbFactory.EntityMap.TableName);
            strsql.Append("(");

            strParam.Append(" values(");

            int index = 0;
            if (entity is EntityBase)
            {
                var baseEntity = entity as EntityBase;

                baseEntity.CreateBy = ApplicationEnvironments.DefaultSession.UserId;
                baseEntity.CreateDate = DateTime.Now;

                baseEntity.LastModifyDate = DateTime.Now;
                baseEntity.LastModifyUserId = ApplicationEnvironments.DefaultSession.UserId;
            }
            foreach (var item in dbFactory.EntityMap.DbFields)
            {
                if ((item.IsPrimaryKey && item.Identifier) || !item.Insert)
                    continue;
                if (item.IsEnabled)
                {
                    var attr = dbFactory.EntityMap.EntityFields.Where(x => x.Name.Equals(item.Name)).FirstOrDefault();
                    var value = dbFactory.GetValue(entity, attr);
                    if (item.AllowDBNull && value == null)
                    {
                        continue;
                    }
                    if (index > 0)
                    {
                        strsql.Append(",");
                        strParam.Append(",");
                    }
                    string parameterName = parameter.GetParameter(item.Name);
                    strsql.Append(item.Name);
                    strParam.Append(parameterName);
                    index++;
                    if (!item.AllowDBNull && value == null)
                    {
                        throw new Exception(item.Name + "不允许为空");
                    }
                  
                    parameter.Add(new DataParameter(item.Name, (item.AllowDBNull&&value == null) ? DBNull.Value : value));
                }
            }
            strsql.Append(")");
            if (dbFactory.EntityMap.Identifier && CurrentProviderType == ProviderType.SqlServer)
            {
                strsql.Append(_provider.DbContext.Identity(dbFactory.EntityMap.PrimaryKey));
            }
            strParam.Append(")");
            strsql.Append(strParam.ToString());
            if (dbFactory.EntityMap.Identifier &&  CurrentProviderType != ProviderType.SqlServer)
            {
                strsql.Append(";" + _provider.DbContext.Identity(""));
            }
            return strsql.ToString();
        }


        public string GetInsert(string tableName, Dictionary<string, object> entity, ref DataParameterCollection parameter)
        {
            if (parameter == null)
                parameter = new DataParameterCollection(this);
            StringBuilder strsql = new StringBuilder();
            StringBuilder strParam = new StringBuilder();
            strsql.Append(" insert into " + tableName);
            strsql.Append("(");
            strParam.Append(" values(");
            int index = 0;
            foreach (var item in entity)
            {
                if (index > 0)
                {
                    strsql.Append(",");
                    strParam.Append(",");
                }
                string parameterName = _provider.DbContext.GetParameter(item.Key);
                strsql.Append(item.Key);
                strParam.Append(parameterName);
                index++;

                parameter.Add(new DataParameter(item.Key, (item.Value == null) ? DBNull.Value : item.Value));
            }
            strsql.Append(")");

            strParam.Append(")");
            strsql.Append(strParam.ToString());

            return strsql.ToString();
        }
        #endregion
        public void Close() {

           // _provider.DbContext.Dispose();
            //_provider.DbContext.Database.CloseConnection();

        }
        public void Open()
        {
           // _provider.DbContext.Database.OpenConnection();
   
        }
        public void Dispose()
        {
            this.Close();
        }

        /// <summary>
        /// 禁用自增
        /// </summary>
        /// <returns></returns>
        public bool Identity_Disabled(string tableName)
        {
            string hql= _provider.DbContext.Identity_Disabled(tableName);
            if (!string.IsNullOrWhiteSpace(hql))
            {
                this.Execute(hql);
            }
            return true;
        }

        /// <summary>
        /// 启用自增
        /// </summary>
        /// <returns></returns>
        public bool Identity_Enable(string tableName)
        {
            string hql = _provider.DbContext.Identity_Enable(tableName);
            if (!string.IsNullOrWhiteSpace(hql))
            {
                this.Execute(hql);
            }
            return true;
        }

        public DbParameter[] GetParameter(List<DataParameter> Parameters)
        {
            return _provider.DbContext.GetParameter(Parameters);
        }
        public DataParameter GetParameter(string name, object value)
        {
            return new DataParameter(name, value) { };
        }
        public string GetParameter(string name)
        {
            return _provider.DbContext.GetParameter(name);
        }

        public string GetLikeParameter(string name)
        {
            return _provider.DbContext.GetLikeParameter(name);
        }
        /// <summary>
		/// 选择自动递增列的最大值
		/// </summary>
		/// <returns></returns>
		public int SelectIdentity(string tableName)
        {

            return _provider.DbContext.SelectIdentity(tableName);

        }


        public DateTime Now
        {
            get
            {
                return _provider.DbContext.Now();
            }
        }
        public DbParameter MakeOutParam(string paramName, DbType DbType, int Size)
        {
            return _provider.DbContext.MakeOutParam(paramName, DbType, Size);
        }

        public DbParameter MakeInParam(string paramName, DbType DbType, int Size, object Value)
        {
            return _provider.DbContext.MakeInParam(paramName, DbType, Size, Value);
        }

        public DbParameter MakeParam(string paramName, DbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            return _provider.DbContext.MakeParam(paramName, DbType, Size, Direction, Value);
        }

        #region 获取数据库中的值
        public List<Dictionary<string, object>> GetTable(string dbName)
        {
            string sql = _provider.DbContext.GetTable(dbName);
            return this.Query<Dictionary<string, object>>(sql, null);
        }
        public List<Dictionary<string, object>> GetView(string dbName)
        {
            string sql = _provider.DbContext.GetView(dbName);
            return this.Query<Dictionary<string, object>>(sql, null);
        }
        public List<Dictionary<string, object>> GetDbColumn(string dbName, string dbServerName, bool isTable)
        {
            string sql = _provider.DbContext.GetDbColumn(dbName, dbServerName, isTable);
            return this.Query<Dictionary<string, object>>(sql, null);
        }

        public LigerGrid GetSource(string dbName, LigerGrid grid)
        {
            string sql = _provider.DbContext.GetSource(dbName);
            int reCordCount = 0;
            Order order = (string.IsNullOrWhiteSpace(grid.sortOrder) ? null : ((grid.sortOrder.ToLower() == "asc") ? Order.Asc(grid.sortName) : Order.Desc(grid.sortName)));
            var result = this.Query<Dictionary<string, object>>(sql, grid.WhereExpression, order, grid.pageIndex, grid.pageSize, ref reCordCount);
            grid.Rows = result;
            if (result != null)
            {
                grid.records = result.Count;
            }
            grid.Total = reCordCount;
            return grid;
        }

        /// <summary>
        /// 生成创建表sql
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dbColumns"></param>
        /// <returns></returns>
        public string CreateTable(string tableName, List<DbColumnAttribute> dbColumns)
        {
            return _provider.DbContext.CreateTable(tableName, dbColumns);
        }

        /// <summary>
        /// 创建列
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columnItem"></param>
        /// <returns></returns>
        public string AddColumn(string tableName, DbColumnAttribute columnItem)
        {
            return _provider.DbContext.AddColumn(tableName, columnItem);
        }
        #endregion
    }
}
